package cn.kvchoi.proactor_aio.server.handlers;

import cn.kvchoi.proactor_aio.server.SessionStateAttachment;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadCompletionHandler implements CompletionHandler<Integer, SessionStateAttachment> {

    private final AsynchronousSocketChannel socketChannel;
    private final ByteBuffer inputBuffer;

    public ReadCompletionHandler(AsynchronousSocketChannel socketChannel, ByteBuffer inputBuffer) {
        this.socketChannel = socketChannel;
        this.inputBuffer = inputBuffer;
    }

    @Override
    public void completed(Integer bytesRead, SessionStateAttachment attachment) {

        System.out.println("Read Handler running on " + Thread.currentThread().getName());

        byte[] buffer = new byte[bytesRead];
        inputBuffer.rewind();
        // Rewind the input buffer to read from the beginning

        inputBuffer.get(buffer);
        String message = new String(buffer);

//        System.out.println("Received message from client : " + message);
//        message = GetRequestParser.getHTTPRequest(message, "200 OK");

        // Echo the message back to client
        ByteBuffer outputBuffer = ByteBuffer.wrap(message.getBytes());
        WriteCompletionHandler writeCompletionHandler = new WriteCompletionHandler(socketChannel);
        socketChannel.write(outputBuffer, attachment, writeCompletionHandler);
    }

    @Override
    public void failed(Throwable exc, SessionStateAttachment attachment) {
        //Handle read failure.....
    }

}